/*This class reads word documents using the Apache POI DLL generated using IKVM form the Apache POI Jar
 * This class needs to be tested and hence will be a part of v1.1 Beta.
 * Also the entire Apache POI framework needs to be explored and better ways to read word and other office
 * documents
 
 * Also there may be a issue with determining the exact position of a search string in the given text file.This
 * is mainly because we are currently segregating the word document section contents using newlines 
*/

using System;
using java.io;
using org.apache.poi.hwpf;
using org.apache.poi.hwpf.extractor;
using org.apache.poi.hwpf.usermodel;
using org.apache.poi.hwpf.model;
using System.Text;
using java.lang;
using Taurus.DocReaders.Interfaces;


namespace Taurus.DocReaders
{
	public class WordReaderPOI : IDocReader
	{
		#region Constructors
		public WordReaderPOI (string wordDocumentName)
		{
			_wordDocumentName = wordDocumentName;
		}
		
		
		#endregion
		
		#region IDocReader members
		
		public void Initialize ()
		{
			using (java.io.FileInputStream wordDocumentInputStream = new java.io.FileInputStream (_wordDocumentName))
			{
				_wordDocument = new HWPFDocument (wordDocumentInputStream);
			}
			
		}

		public string ReadDocument ()
		{
			return ReadInternal ();
			
		}

		public void Close ()
		{
			return;
		}

		#endregion
		
		#region Private member functions
		
		private string ReadInternal ()
		{
			System.Text.StringBuilder documentText = new System.Text.StringBuilder ();
			
			
			Range documentRange = _wordDocument.getRange ();
			
			
			for (int sectionCounter = 0; sectionCounter < documentRange.numSections (); sectionCounter++) {
				Section s = documentRange.getSection (sectionCounter);
				
				//loop through all the paragraphs in the section and print out the text
				for (int paragraphCounter = 0; paragraphCounter < s.numParagraphs (); paragraphCounter++) {
					Paragraph p = s.getParagraph (paragraphCounter);
					
					for (int charRunCounter = 0; charRunCounter < p.numCharacterRuns (); charRunCounter++) {
						CharacterRun run = p.getCharacterRun (charRunCounter);
						documentText.Append (run.text ());
					
					}
					documentText.Append (Environment.NewLine);
				}
			}
			
			return documentText.ToString ();
		}
		
		#endregion
		
		
		#region Private members
		
		private string _wordDocumentName;
		
		HWPFDocument _wordDocument;
		
		
		
		#endregion
	}
}

